<template>
	<view class="container">
		<!-- 自定义导航栏 -->
		<CustomNavBar 
			:show-back="true" 
			:show-logo="false" 
			title="仓库管理"
			background-color="#ffffff"
			@back="handleBack"
			ref="navBarRef"
		/>
		<view class="content-wrapper" :style="{ paddingTop: navHeight + 'px' }">
        <!-- 功能按钮区域 -->
        <view class="function-buttons">
            <view 
                class="button-item" 
                v-for="button in buttonList" 
                :key="button.id"
                @click="handleButtonClick(button.type, button.text)"
            >
                <text class="button-text">{{ button.text }}</text>
            </view>
        </view>
    </view>
    
    <!-- 右侧抽屉 -->
    <RightDrawer :nav-height="navHeight" />
       </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import http from '../../../utils/request'
import { onLoad, onReady, onUnload, onBackPress } from '@dcloudio/uni-app'
import CustomNavBar from '@/components/CustomNavBar.vue'
import { useUserStore } from '@/store/user'


const navHeight = ref(0)
const navBarRef = ref(null)

// 初始化用户store
const userStore = useUserStore()

const code = ref("001")

// 平台类型：app 或 wechat
const platform = ref('')

// 按钮数据列表 - 只保留文字和类型
const buttonList = ref([
  { id: 1, text: '出库', type: 'outbound' },
  { id: 2, text: '入库', type: 'inbound' },
  { id: 3, text: '商品', type: 'product' },
  { id: 4, text: '库存', type: 'inventory' },
  { id: 5, text: '账单', type: 'billing' },
  { id: 6, text: '流水', type: 'transaction' }
])

// 处理返回按钮点击
const handleBack = () => {
  console.log('仓库页面返回按钮被点击')
  uni.navigateBack({
    delta: 1
  })
}

// 统一处理功能按钮点击 - 跳转到对应页面
const handleButtonClick = (type, text) => {
  console.log(`点击了${text}按钮，类型：${type}`)
  
  // 预留功能：物资管理和盘点管理
  if (type === 'material' || type === 'check') {
    uni.showToast({
      title: '该功能尚未开放',
      icon: 'none',
      duration: 2000
    })
    return
  }
  
  // 页面路由映射
  const pageRoutes = {
    'outbound': '/pages/warehouse/outbound/index',
    'inbound': '/pages/warehouse/inbound/index',
    'product': '/pages/warehouse/product/index',
    'inventory': '/pages/warehouse/inventory/index',
    'billing': '/pages/warehouse/billing/index',
    'transaction': '/pages/warehouse/transaction/index',
  }
  
  // 跳转到对应页面
  const route = pageRoutes[type]
  if (route) {
    uni.navigateTo({
      url: route,
      success: () => {
        console.log(`成功跳转到${text}页面`)
      },
      fail: (err) => {
        console.error(`跳转失败:`, err)
        uni.showToast({
          title: '页面跳转失败',
          icon: 'error'
        })
      }
    })
  } else {
    console.log('未知按钮类型')
  }
}

const getWarehouseInfo = async (code) => {
  try {
    const userInfo = userStore.getUserInfo()
    console.log('输入参数:', {
      userRowid: userInfo.rowid,
      code: userStore.getWarehouseCode(),
    });
    
 const res = await http.post('https://www.dachen.vip/api/workflow/hooks2/NjhjZTNiYTYzN2EzYTM4OTFhYjEyNDA3',{
      userRowid: userStore.getUserInfo().rowid,
      code: code,
    })
if(res){
  console.log('仓库信息:', res)
  
  // 将仓库信息存储到全局store中
  if (res.data) {
    try {
      const warehouseData = typeof res.data === 'string' ? JSON.parse(res.data) : res.data
      userStore.setWarehouseInfo(warehouseData)
      console.log('仓库信息已存储到全局store:', userStore.getWarehouseInfo())
      console.log(userStore.getWarehouseInfo().sh_signIn)
    } catch (parseError) {
      console.error('解析仓库信息失败:', parseError)
    }
  }
}
  } catch (error) {
    console.error('获取仓库信息失败:', error)
  }
}



onLoad((query) => {
  // 解析仓库链接地址
	if (query && query.code) {
		try {
			code.value = decodeURIComponent(query.code)
      // 存储仓库编码到store
      userStore.setWarehouseCode(code.value)
      console.log('仓库编码已存储到store:', userStore.getWarehouseCode())
       getWarehouseInfo(query.code)
		} catch (e) {
			code.value = query.code
      // 存储仓库编码到store
      userStore.setWarehouseCode(code.value)
      console.log('仓库编码已存储到store:', userStore.getWarehouseCode())
		}
	}
})

// 监听平台类型
const detectPlatform = () => {
  // #ifdef APP-PLUS
  platform.value = 'app'
  // #endif
  
  // #ifdef MP-WEIXIN
  platform.value = 'wechat'
  // #endif
  
  console.log('当前平台类型:', platform.value)
}

onReady(() => {
  // 检测平台类型
  detectPlatform()
  // 获取导航栏高度
  if (navBarRef.value) {
    if(platform.value === 'wechat'){
    navHeight.value = navBarRef.value.totalNavHeight + 54 || 0
    }
    else{
      navHeight.value = navBarRef.value.totalNavHeight  || 0
    }
    
    console.log('仓库页面导航栏高度:', navHeight.value)
  }
  
})
</script>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100vh;
  position: relative;
  .content-wrapper {
    height: 100%;
    padding: 20rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    
    .function-buttons {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 2%;
      padding: 20rpx 0;
      align-content: flex-start; // 顶部对齐，不拉伸
      
      .button-item {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 47%; // 两列布局
        height: calc((100% - 12%) / 7); // 七行布局，每行高度
        background-color: #4CAF50; // 绿色
        border-radius: 8rpx;
        transition: background-color 0.2s ease;
        
        &:active {
          background-color: #45a049;
        }
        
        .button-text {
          font-size: 32rpx;
          color: #ffffff;
          font-weight: bold;
          text-align: center;
        }
      }
    }
  }
}
</style>
